/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.caf.data.jpa.repository;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.iec.caf.data.jpa.repository.support.CafJpaLanguageThreadHolder;
import io.iec.edp.caf.commons.core.SerializerFactory;
import io.iec.edp.caf.commons.core.enums.SerializeType;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * This is {@link CafI18nColumnDict}.
 *
 * @author yisiqi
 * @since 1.0.0
 */
@Slf4j
public class CafI18nColumnDict implements Serializable {

    @Getter
    @Setter
    private Map<String, Map<String, String>> colI18nValues = new HashMap<>();

    public Optional<String> get(String column, String lang) {
        return Optional.ofNullable(colI18nValues.get(column)).map(i18nValues -> i18nValues.get(lang));
    }

    public void put(String column, String lang, String value) {
        Map<String, String> i18nValues = colI18nValues.get(column);
        if (i18nValues == null) {
           i18nValues = new HashMap<>();
        }
        i18nValues.put(lang, value);
        colI18nValues.put(column, i18nValues);
    }

    /**
     * 返回平铺的带语言后缀列名
     * 如：name 属性有两个多语言选项 _en 和 _zh, 值分别为 kettle 和 水壶，则返回
     * name_en: kettle
     * name_zh: 水壶
     * */
    @JsonIgnore
    public Map<String, String> getAllColumnsDict() {
        Map<String, String> result = new HashMap<>();
        Map<String,String> langs = CafJpaLanguageThreadHolder.getLanguages();
        colI18nValues.entrySet().forEach(column -> {
            Map<String, String> i18nValues = column.getValue();
            i18nValues.entrySet().forEach(entry -> {
                var curLang = langs.get(entry.getKey());
                if(curLang!=null){
                    String suffix = curLang.replaceAll("^_", "");
                    result.put(column.getKey() + "_" + suffix, entry.getValue());
                }else{
                    log.info("当前要保存的语言是："+entry.getKey()+",当前线程上下文可用语言列表是："+ SerializerFactory.getSerializer(SerializeType.Json).serializeToString(langs));
                }

            });
        });
        return result;
    }

    /**
     * 返回指定column的多语值(key为语言编号）
     * 如：
     * zh-chs: 水壶
     * en: kettle
     * @param column
     * @return
     */
    public Map<String,String> getI18nValues(String column){
        Map<String, String> i18nValues = colI18nValues.get(column);
        return i18nValues;
    }

    //自定义序列化
    private void writeObject(ObjectOutputStream out) throws IOException {
        //写入反序后的密码，当然我们也可以使用其他加密方式。这样别人打开文件，看到的就不是真正的密码，更安全。
        out.writeObject(this.colI18nValues.get("en"));
    }

    /**
     * 自定义反序列化
     * @param in
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        this.colI18nValues = (Map<String, Map<String, String>>)in.readObject();
    }
}
